package keeto.com.vn.classified.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import keeto.com.vn.classified.config.IConstant;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.network.IProtocol;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterActivity extends Activity implements OnClickListener {
	private String TAG = "RegisterActivity";
	
	private static final String STATE_KEY_USER_NAME = "keeto.com.vn.classifeld.ui.Register.UserName";
	private static final String STATE_KEY_PASSWORD = "keeto.com.vn.classifeld.ui.Register.Password";
	private static final String STATE_KEY_CONFIRMPASSWORD = "keeto.com.vn.classifeld.ui.Register.Confirm";

	private static final int REGISTER_PROGRESS_DIALOG = 0;
	private static final int REGISTER_LOGON_MESSAGE = 1;
	private static final int REGISTER_NOTICE_MESSAGE = 2;
	protected static final int DIALOG_MESSAGE_DIALOG = 4;

	private ImageButton btnBack;
	private ImageButton btnHome;
	private CheckBox agreeLicenseCheckBox;
	private EditText userName;
	private EditText password;
	private EditText confirmPassword;
	private EditText phoneNumber;
	private Button signUpButton;
	private TextView service_agreement_term_text;
	private String mNoticeMessage = "";
	private Dialog mNoticeDialog = null;
	String emailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
	 private RegisterHandler mHandler = new RegisterHandler();

	private static final String MSG_EXTRA_USERNAME = "UserName";
	private static final String MSG_EXTRA_PASSWORD = "Password";
	private static final String MSG_EXTRA_RETURNCODE = "returnCode";

	 private RegisterListener mListener = new RegisterListener();

	private static  boolean D= MainApplication.DEBUG;
	 private static InUIThreadHandler mReturnCodeHandler = null;

	public static void actionLaunch(Context context) {
		Intent i = new Intent(context, RegisterActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register_layout);
		initUIComponent();
	}

	private void initUIComponent() {
		btnBack = (ImageButton) findViewById(R.id.btn_title_na_menu);
		btnHome = (ImageButton) findViewById(R.id.btn_title_logo_home);
		agreeLicenseCheckBox = (CheckBox) findViewById(R.id.check_agree_license);
		userName = (EditText) findViewById(R.id.register_user_name);
		password = (EditText) findViewById(R.id.register_password);
		confirmPassword = (EditText) findViewById(R.id.register_confirm_password);
		phoneNumber=(EditText) findViewById(R.id.register_phone);
		service_agreement_term_text = (TextView) findViewById(R.id.tv_check_agree_license);
		signUpButton = (Button) findViewById(R.id.register_sign_up);

		btnBack.setOnClickListener(this);
		btnHome.setOnClickListener(this);
		signUpButton.setOnClickListener(this);
		service_agreement_term_text.setMovementMethod(LinkMovementMethod
				.getInstance());
		service_agreement_term_text.setText(Html
				.fromHtml(getResources().getString(
						R.string.tv_link_register_policy)
						+ " & "
						+ getResources().getString(
								R.string.tv_link_register_securrity)));
		 userName.addTextChangedListener(userNamewatcher);
		 password.addTextChangedListener(passwordwatcher);
		 confirmPassword.addTextChangedListener(confirmPasswordWatcher);
	}
	
	
	class RegisterHandler extends Handler {

		public void registerBuiltinAccount(String userName, String password, String phone) {
			int returnCode = IConstant.UNINITIALIZED_INT;
			ClassifiedCore.getInstance(getApplication()).taskRegister(mListener,userName,
					password, phone);
		}

		public void ShowProgressDialog() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					RegisterActivity.this.showDialog(REGISTER_PROGRESS_DIALOG);
				}
			});
		}



		public void showLogonMessageDialog() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					showDialog(REGISTER_LOGON_MESSAGE);
				}
			});
		}
		public void DismissProgressDialog() {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					RegisterActivity.this
					.dismissDialog(REGISTER_PROGRESS_DIALOG);
				}
			});
		}

	}
	public Dialog createLogonFailedDialog() {
		Dialog dialog = new AlertDialog.Builder(RegisterActivity.this)
		.setIcon(R.drawable.ic_dialog_menu_generic)
		.setMessage(mNoticeMessage)
		.setTitle(R.string.notice_title)
		.setPositiveButton(R.string.text_ok,
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog,
					int whichButton) {

			}
		}).create();
		return dialog;

	}
	public Dialog createRegisterOKDialog() {
		Dialog dialog = new AlertDialog.Builder(RegisterActivity.this)
		.setIcon(R.drawable.ic_dialog_menu_generic)
		.setMessage(
				getString(R.string.register_ok_message, userName
						.getText().toString(), password.getText()
						.toString()))
						.setTitle(R.string.register_ok_title)
						.setPositiveButton(R.string.text_login,
								new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int whichButton) {

								// to logon activity
								LoginActivity.actionLogonWithRegisteredInfo(
										RegisterActivity.this, userName
										.getText().toString(), password
										.getText().toString());
								finish();

							}
						}).create();
		return dialog;

	}
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case REGISTER_PROGRESS_DIALOG:
			return ProgressDialog.show(this,
					getString(R.string.register_title_request_server),
					getString(R.string.register_message_please_wait));
		case REGISTER_LOGON_MESSAGE:
			return createRegisterOKDialog();

		case REGISTER_NOTICE_MESSAGE:
			return createLogonFailedDialog();

		case DIALOG_MESSAGE_DIALOG:
			return mNoticeDialog;
		}
		return super.onCreateDialog(id);
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		if (D)
			Log.w(TAG, "***onPrepareDialog");
		if (id == DIALOG_MESSAGE_DIALOG) {
			mNoticeDialog = null;
			mNoticeDialog = createLogonFailedDialog();
			super.onPrepareDialog(id, mNoticeDialog);
			return;
		}
		super.onPrepareDialog(id, dialog);
	}
	class RegisterListener extends ClassifiedListener {

		@Override
		public void finishRegister(final int returnCode, String username,
				String password) {
		runOnUiThread(new Runnable() {
			public void run() {
				if (returnCode == IProtocol.STATUS_CODE_OK_200) {

					mHandler.DismissProgressDialog();
					mHandler.showLogonMessageDialog();

				} else if(returnCode==IProtocol.STATUS_CODE_ACCOUNT_ALREADY_EXIST_672) {

					mHandler.DismissProgressDialog();
					String msg= getString(R.string.txt_email_already_exist);
					Toast.makeText(RegisterActivity.this, msg, Toast.LENGTH_SHORT).show();
//					mReturnCodeHandler.takeActionByReturnCode(
//							RegisterActivity.this, returnCode, false);

				}
			}
		});
			super.finishRegister(returnCode, username, password);

		}

	}

	private void setErrorMsg(String msg,EditText viewId)
	{
		int ecolor = Color.RED; // whatever color you want
		String estring = msg;
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
		ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
		viewId.setError(ssbuilder);

	}

	private void setErrorMsgCheckBox(String msg,CheckBox viewId)
	{
		int ecolor = Color.RED; // whatever color you want
		String estring = msg;
		ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
		SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
		ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
		viewId.setError(ssbuilder);

	}
	private void registerBuiltinAccount() {

		if (!agreeLicenseCheckBox.isChecked()) {
			//			agreeLicenseCheckBox
			//					.setError(getString(R.string.register_agree_license_requirement));
			setErrorMsgCheckBox(getString(R.string.register_agree_license_requirement), agreeLicenseCheckBox);
			return;
		}

		// validation
		if (!userName.getText().toString().matches(emailPattern))
				 {

			//			userName.setError(getString(R.string.register_id_requirement));
			setErrorMsg(getString(R.string.register_id_requirement),userName);
			userName.requestFocus();
			return;
		}
		if (password.getText().toString().equals("")
				|| password.getText().toString().length() < 6
				|| password.getText().toString().length() > 16) {

			//			password.setError(getString(R.string.register_password_requirement));
			setErrorMsg(getString(R.string.register_password_requirement),password);
			password.requestFocus();
			return;
		}
		if (!phoneNumber.getText().toString().equals("")
				&& phoneNumber.getText().toString().length() < 10
				) {

			//			phoneNumber.setError(getString(R.string.register_password_requirement));
			setErrorMsg(getString(R.string.register_phone_requirement),phoneNumber);
			password.requestFocus();
			return;
		}

//		// username validation
//		Pattern p = Pattern.compile("^[a-z0-9A-Z_]{6,20}$");
//		Matcher m1 = p.matcher(userName.getText().toString());
//		boolean isMatch = m1.matches();
//		if (!isMatch) {
//			//			userName.setError(getString(R.string.register_invalid_username));
//			setErrorMsg(getString(R.string.register_invalid_username),userName);
//			userName.requestFocus();
//			return;
//		}

		// password validation
		Pattern p2 = Pattern.compile("^[a-z0-9A-Z]{6,20}$");
		Matcher m2 = p2.matcher(password.getText().toString());
		boolean isMatch2 = m2.matches();
		if (!isMatch2) {
			//			password.setError(getString(R.string.register_invalid_password));
			setErrorMsg(getString(R.string.register_invalid_password),password);
			password.requestFocus();
			return;
		}

		if (!password.getText().toString()
				.equals(confirmPassword.getText().toString())) {
			//			confirmPassword
			//					.setError(getString(R.string.register_confirm_password_requirement));
			setErrorMsg(getString(R.string.register_confirm_password_requirement),confirmPassword);
			confirmPassword.requestFocus();
			return;
		}

		mHandler.ShowProgressDialog();
		mHandler.registerBuiltinAccount(userName.getText().toString(), password
				.getText().toString(),phoneNumber.getText().toString());

	}


	private TextWatcher userNamewatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			if(s != null && s.length() > 0 && userName.getError() != null) {
				userName.setError(null);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

		}
	};

	private TextWatcher passwordwatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			if(s != null && s.length() > 0 && password.getError() != null) {
				password.setError(null);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

		}
	};
	private TextWatcher confirmPasswordWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			if(s != null && s.length() > 0 && confirmPassword.getError() != null) {
				confirmPassword.setError(null);
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub

		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub

		}
	};
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.register_sign_up:
			registerBuiltinAccount();
			break;
		case R.id.btn_title_na_menu:
			finish();
			break;
		case R.id.btn_title_logo_home:
			HomeClassifeldActivity.actionLaunch(this);
			break;
		default:
			break;
		}

	}
}
